<template>
  <div class="app-container" >
    <el-row :gutter="20">

      <!--用户数据-->
      <el-col :span="20" :xs="24">


        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button
              type="primary"
              plain
              icon="el-icon-plus"
              size="mini"
              @click="handleAdd"
            >新增</el-button>
          </el-col>


        </el-row>

        <!--    展示table    -->

        <el-table   v-loading="loading" :data="projectsName" @selection-change="handleSelectionChange">


          <el-table-column label="项目编号" align="center" key="id"   prop="id" v-if="columns[0].visible" />
          <el-table-column label="项目名称" align="center" key="project_name" prop="project_name" v-if="columns[1].visible" :show-overflow-tooltip="true" />
          <el-table-column label="工作类型" align="center" key="role" prop="role" v-if="columns[2].visible" :show-overflow-tooltip="true" />


          <el-table-column label="操作" align="center" width="160" class-name="small-padding fixed-width">
            <template slot-scope="scope" v-if="scope.row.role=='leader'">
              <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)" v-hasPermi="['system:user:remove']">
                删除
              </el-button>
              <el-button size="mini" type="text" icon="el-icon-d-arrow-right el-icon--right" @click="handleAddPeople(scope.row)"
                         v-hasPermi="['system:user:remove']" >
                添加
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <pagination
          v-show="total>0"
          :total="total"
          :page.sync="queryParams.pageNum"
          :limit.sync="queryParams.pageSize"
          @pagination="getList"
        />
      </el-col>
    </el-row>

    <!-- 新增项目 -->
    <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body>
      <el-form ref="form" :model="form"  label-width="80px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="项目名称" prop="projectName">
              <el-input v-model="form.projectName" placeholder="请输入项目名称" maxlength="30" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="工作类型">
              <el-select v-model="form.workType" placeholder="请选择工作类型">
                <el-option disabled label="组长">组长</el-option>
                <!--    <el-option v-for="(dict,index) in worktype" :key="index" :value="dict" ></el-option>-->
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!--  添加组员  -->
    <el-dialog :visible.sync="open2" title="添加项目成员">
      <el-row>
        <el-select v-model="form.selectUser" placeholder="请选择组员" >
          <el-option v-for="item in memberlist" :value="item.userId" :label="item.nickName" @click.native="bindSelectUserName(item.nickName,item.userId)">
          </el-option>
        </el-select>
      </el-row>
      <el-row style="margin-top: 20px;">
        <el-select v-model="form.selectUserRole" placeholder="请选择工作类型">
          <el-option v-for="item in worktype" :value="item" :label="item" >
          </el-option>
        </el-select>
      </el-row>
      <br/>
      <el-row>
        <label>该项目成员有：</label>
      </el-row>
      <el-row style="margin-top: 10px;">
        <div>
          <el-tag style="margin-top: 10px;" :key="tag" v-for="tag in dynamicTags" closable :disable-transitions="false" @close="handleClose(tag)">
            {{tag}}
          </el-tag>
          <el-input class="input-new-tag" v-if="inputVisible" v-model="inputValue" ref="saveTagInput" size="small">
          </el-input>
        </div>
      </el-row>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="addSelectUser">确 定</el-button>
        <el-button @click="cancel2">取 消</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import { listUser, getUser, delUser, addUser, updateUser, resetUserPwd, changeUserStatus } from "@/api/system/user";
import { getToken } from "@/utils/auth";
import { treeselect } from "@/api/system/dept";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import axios from "axios";
import {
  addnewproject,
  addselectuser,
  deleteproject, deleteprojectstaff, getmember,
  getprojectlist, getprojectstaff,
  getuserinfo,
  getuserrole,
  test,
} from "@/api/system/daily";

export default {
  name: "User",
  components: { Treeselect },
  data() {
    return {
      test: "dsa",
      //工作类型
      worktype:["运营","前端","后端","后勤"],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 总条数
      total: 0,
      // 用户表格数据
      userList: null,
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 是否显示弹出层
      open2: false,
      // 默认密码
      initPassword: undefined,
      // 日期范围
      dateRange: [],
      // 角色选项
      roleOptions: [],
      // 表单参数
      form: {

      },
      defaultProps: {
        children: "children",
        label: "label"
      },
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        userName: undefined,
        status: undefined,
        deptId: undefined
      },
      // 列信息
      columns: [
        { visible: true },
        { visible: true },
        { visible: true },
      ],
      //成员标签
      dynamicTags:[],
      inputVisible: false,
      inputValue: '',
      addUserList:undefined,
      projectsName:[],
      userid:"",
      //传参相关
      newProject:{
        project_name:"",
        leader_id:"",
        remark:"",
      },
      addmember: {
        staff_id:"",
        project_id:"",
        role:"",
      },
      thisprojectstaff:[],
      deleteProjectStaff:{
        staff_id:"",
        project_id:"",

      },
      memberlist:[],
    };
  },
  created() {
    this.getUserinfo();
    this.getList();

  },
  methods: {


    // 查询当前用户项目列表
    getList() {
      this.projectsName=[];
      this.loading=true;
      getprojectlist().then(response =>{
        //console.log(response);
        //添加项目角色
        for(let i =0;i<response.rows.length;i++){

          this.temp=getuserrole({
            staff_id:this.userid,
            project_id:response.rows[i].id,
          }).then(response2=>{
            this.projectsName.push({
              id:response.rows[i].id,
              project_name:response.rows[i].project_name,
              role:response2.data.role,
            });
          });

        }
        //console.log(this.projectsName);
        this.loading=false;
      });


    },
    cancel() {
      this.open = false;
    },
    cancel2() {
      this.open2 = false;
    },
    // 表单重置
    reset() {
      this.form = {
        projectName: "",
        workType:"",
        selectUser:"",
        selectUserRole:"",
        addProjectId:"",
        selectUserName:"",
        selectUserId:"",
        selectProjectId:"",
      };
      this.resetForm("form");
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.userId);
      this.single = selection.length != 1;
      this.multiple = !selection.length;
    },
    //得到用户id
    async getUserinfo(){
      this.loading=true;
      await getuserinfo().then(response => {
        this.userid=response.user.userId;
        this.loading = false;
      });
      await this.getMember();
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.open = true;
      this.getUserinfo();

    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      const userId = row.userId || this.ids;
      getUser(userId).then(response => {
        this.form = response.data;
        this.roleOptions = response.roles;
        this.form.postIds = response.postIds;
        this.form.roleIds = response.roleIds;
        this.open = true;
        this.title = "修改用户";
        this.form.password = "";
      });
    },
    /** 提交按钮 */
    submitForm() {

      this.newProject.project_name=this.form.projectName
      this.newProject.leader_id=this.userid;
      addnewproject(this.newProject).then(response =>{
        this.getList();
      });
      this.open=false;
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      //console.log(row.id);
      this.$modal.confirm('是否确认删除项目编号为"' + row.id + '"的数据项？').then(function() {
        //删除数据库中记录
        deleteproject(row.id).then(response =>{

        });
        //return delUser(userIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    //添加成员时获取用户列表
    async getUserList(){
      await listUser().then(response =>{

        //获取用户名  userlist:组员id
        for(let i =0 ;i< response.rows.length ; i++){
          for(let j =0 ;j<this.userList.length ; j ++){
              if(this.userList[j]==response.rows[i].userId){
                this.memberlist.push({
                  userId:this.userList[j],
                  nickName:response.rows[i].nickName,

                });
              }
          }

        }
        //console.log("userlist:-----"+JSON.stringify(this.userList));

      });
      //console.log(this.addUserList);
    },
    getMember(){

        getmember(this.userid).then(response => {
          this.userList=response.rows;
          //console.log(this.memberlist);


        });



    },
    //添加项目成员
    async handleAddPeople(row){
      this.memberlist=[],
      this.dynamicTags=[];
      this.thisprojectstaff=[];
      this.open2=true;
      this.form.addProjectId=row.id;
      await this.getUserList();
      getprojectstaff(row.id).then(response =>{
        let temp=response.rows; //thisprojectstaff
        //找到response中id对应的name用于tag显示
        //console.log("temp---------"+temp);
        for(let i =0; i< temp.length;i++){
          for(let j =0 ;j <this.memberlist.length;j++){
            if(temp[i]==this.memberlist[j].userId&&temp[i]!=this.userid){
              this.thisprojectstaff.push({
                userid:temp[i],
                nickname:this.memberlist[j].nickName,
              });
            }
          }
        }
        //console.log("thisprojectstaff---------"+JSON.stringify(this.thisprojectstaff));
        this.dynamicTags=[];
        for(let i=0;i<this.thisprojectstaff.length;i++){
          this.dynamicTags.push(this.thisprojectstaff[i].userid+":"+this.thisprojectstaff[i].nickname);
        }
      });
    },
    //添加选中成员
    addSelectUser(){
      //console.log(this.form.selectUser);
      let flag=1;
      for(let i =0;i<this.dynamicTags.length;i++){
        if(this.dynamicTags[i].split(':')[1]==this.form.selectUserName)
        {
          flag=0;
          alert("此用户已经添加了😓");
        }
      }
      if(flag){
        this.dynamicTags.push(this.form.selectUserId+":"+this.form.selectUserName);
        this.addmember.project_id=this.form.addProjectId;
        this.addmember.staff_id=this.form.selectUser;
        this.addmember.role=this.form.selectUserRole;
        console.log(this.addmember);
        addselectuser(this.addmember).then(response =>{
          this.$modal.msgSuccess("添加成功");
        });
      }

    },
    //删除已添加的项目成员
    handleClose(tag) {
      //this.form.addProjectId
      this.deleteProjectStaff.staff_id=tag.split(':')[0];
      this.deleteProjectStaff.project_id=this.form.addProjectId;
      this.dynamicTags.splice(this.dynamicTags.indexOf(tag), 1);
      deleteprojectstaff(this.deleteProjectStaff).then(response =>{
        this.$modal.msgSuccess("删除成功");
      });
    },
    //获得选中的用户名称
    bindSelectUserName(name,id){
      //console.log(name);
      this.form.selectUserName=name;
      this.form.selectUserId=id;
    },



  }
};
</script>





<style>
.el-tag + .el-tag {
  margin-left: 10px;
}
.input-new-tag {
  width: 90px;
  margin-left: 10px;
  vertical-align: bottom;
}
</style>
